package org.platform.tool.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * Json 工具类
 *
 * @author FengJie
 * @date 2018/5/15
 */
public class JsonUtils {
    /**
     * json转对象(不使用注解)
     *
     * @param json
     * @param t
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T jsonToBean(String json, Class<T> t) throws IOException {
        return jsonToBean(json, t, false);
    }

    /**
     * 对象转json(不使用注解)
     *
     * @return
     * @throws IOException
     */
    public static String beanToJson(Object bean) throws JsonProcessingException {
        return beanToJson(bean, false);
    }

    /**
     * json转对象(不使用注解)
     *
     * @param json
     * @param useAnnotations 是否启动注解
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T jsonToBean(String json, Class<T> t, boolean useAnnotations) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.USE_ANNOTATIONS, useAnnotations);
        return objectMapper.readValue(json, t);
    }

    /**
     * 对象转json(不使用注解)
     *
     * @param useAnnotations 是否启动注解
     * @return
     * @throws IOException
     */
    public static String beanToJson(Object bean, boolean useAnnotations) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.USE_ANNOTATIONS, useAnnotations);
        return objectMapper.writeValueAsString(bean);
    }
}
